<template>
  <div class>
    <div class="card tr mb2">
      <el-tooltip content="显示字段筛选" placement="bottom" effect="light">
        <el-popover placement="bottom" width="200" trigger="click">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <el-checkbox-group v-model="showItemList" @change="handleCheckedChange">
            <el-checkbox v-for="(item,key) in allItemList" :key="key" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <el-button slot="reference" icon="el-icon-menu" size="mini" type="primary" circle></el-button>
        </el-popover>
      </el-tooltip>

      <el-tooltip content="展开/收起表单" placement="bottom" effect="light">
        <el-button
          icon="el-icon-search"
          @click="formShow= !formShow"
          size="mini"
          type="primary"
          circle
        ></el-button>
      </el-tooltip>
      <el-tooltip content="下载当前表格数据" placement="bottom" effect="light">
        <el-button
          icon="el-icon-download"
          @click="handleDownload"
          size="mini"
          type="primary"
          circle
        ></el-button>
      </el-tooltip>

      <el-button size="mini" type="primary" icon="el-icon-plus" @click="showDialog">添加</el-button>
    </div>
    <div class="card" v-show="formShow">
      <el-form
        size="mini"
        :style="style"
        :model="ruleForm"
        ref="ruleForm"
        inline
        label-width="100px"
        class="demo-ruleForm"
      >
        <my-form-item label="角色名称" prop="roleName">
          <el-input size="mini" v-model="ruleForm.roleName"></el-input>
        </my-form-item>
        <my-form-item label="角色编码" prop="roleCode">
          <el-input size="mini" v-model="ruleForm.roleCode"></el-input>
        </my-form-item>
        <my-form-item label="启用状态" prop="roleEnabledState">
          <el-select size="mini" v-model="ruleForm.roleEnabledState">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </my-form-item>
        <my-form-item>
          <el-button size="mini" type="primary" @click="submitForm('ruleForm')">查询</el-button>
          <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
        </my-form-item>
      </el-form>
    </div>
    <el-table ref="dragTable" row-key="id" :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
      <el-table-column
        :formatter="item.formatter"
        v-for="(item,index) in allItemList"
        :key="index"
        :label="item.name"
        v-if="item.show"
      >
        <template slot-scope="scope">
          <template v-if="!item.formatter">{{ scope.row[item.key] }}</template>
          <template v-else>
            <span v-text="item.formatter(scope.row, item)"></span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showEditDialog(scope.$index, scope.row)">编辑</el-button>
          <el-button type="primary" size="mini" @click="showUser(scope.row)">用户</el-button>
          <el-button type="primary" size="mini" @click="privilege(scope.row)">权限</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="card tr">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="currentPage"
        :page-sizes="[ 10, 20,30, 40]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
      ></el-pagination>
    </div>
    <!-- --------------------------------------------------------添加弹出框 -->
    <el-dialog title="角色管理" width="300px" :visible.sync="dialogFormVisible">
      <el-form :model="form" size="mini" label-width="80px" ref="addForm" :rules="rules">
        <my-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="角色属性" prop="roleType" :label-width="formLabelWidth">
          <el-input v-model="form.roleType" autocomplete="off"></el-input>
        </my-form-item>

        <my-form-item label="角色编码" prop="roleCode" :label-width="formLabelWidth">
          <el-input v-model="form.roleCode" disabled autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item
          label="启用状态"
          :label-width="formLabelWidth"
          width="100%"
          prop="roleEnabledState"
        >
          <el-select v-model="form.roleEnabledState" style="width:400px;">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </my-form-item>
        <my-form-item label="备注" prop="remark" :label-width="formLabelWidth" width="100%">
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </my-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleAdd()" size="mini">确 定</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------------------------编辑弹出框 -->
    <el-dialog title="角色管理" width="300px" :visible.sync="dialogEditVisible">
      <el-form :model="editForm" size="mini" label-width="80px" ref="editForm" :rules="rules">
        <my-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="角色属性" :label-width="formLabelWidth">
          <el-input v-model="editForm.roleType" autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item label="角色编码" :label-width="formLabelWidth">
          <el-input v-model="editForm.roleCode" disabled autocomplete="off"></el-input>
        </my-form-item>
        <my-form-item
          label="启用状态"
          :label-width="formLabelWidth"
          width="100%"
          prop="roleEnabledState"
        >
          <el-select v-model="editForm.roleEnabledState" style="width:400px;">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </my-form-item>
        <my-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </my-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogEditVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- ---------------------------------------------------------用户弹出框 -->
    <el-dialog title="用户" :visible.sync="dialogUser" width="80%">
      <div class="card" style>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="dialogAllUser=true">添加</el-button>
      </div>
      <el-table :data="userTableData" border style="width: 100%">
        <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
        <el-table-column align="center" prop="username" label="用户名"></el-table-column>
        <el-table-column align="center" prop="realName" label="真实姓名"></el-table-column>
        <el-table-column align="center" prop="mobile" label="手机号码"></el-table-column>
        <el-table-column align="center" prop="telephone" label="电话号码"></el-table-column>
        <el-table-column align="center" prop="email" label="电子邮箱"></el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card" style="text-align:right;">
        <el-pagination
          @size-change="sizeChange1"
          @current-change="currentChange1"
          :current-page="currentPage1"
          :page-sizes="[ 10, 20,30, 40]"
          :page-size="pageSize1"
          background
          layout="total, sizes, prev, pager, next"
          :total="total1"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUser = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="dialogUser = false" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    <qx-dialog ref="qxDL" :roleId="roleId"></qx-dialog>

    <el-dialog title="所有用户" width="80%" :visible.sync="dialogAllUser" :fullscreen="fullscreen">
      <users ref="user" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="addUserOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from "sortablejs";
// import { getList, deleteItem, addItem, editItem } from "./function";
import qxDialog from "./components/qxgl";
import { getUserListByRoleId, delRoleUser } from "../permission/function";
import users from "@/components/checkUser/uesrs.vue";
import { addRoleUser } from "../permission/function";
const defaultFormThead = [
  { key: "roleName", name: "角色名称", show: true },
  { key: "roleType", name: "角色属性", show: true },
  { key: "roleCode", name: "角色编码", show: true },
  { key: "remark", name: "备注", show: true },
  {
    key: "roleEnabledState",
    show: true,
    name: "启用状态",
    formatter: row => {
      if (row.roleEnabledState == 1) {
        return "启用";
      } else {
        return "禁用";
      }
    }
  }
];
export default {
  components: {
    users,
    qxDialog
  },
  data() {
    return {
      fullscreen: false,
      checkAll: true,
      isIndeterminate: false,
      sortable: null,
      allItemList: defaultFormThead,
      showItemList: defaultFormThead,
      formShow: false,
      roleId: "",
      key: 1,
      dialogFormVisible: false,
      dialogEditVisible: false,
      dialogUser: false,
      dialogAllUser: false,
      offForm: true, //是否折叠
      folding: false, //表单是否超过一行
      formLabelWidth: "80px",
      tableData: [],
      tableData1: [],
      userTableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      total1: 0,
      pageSize1: 10,
      currentPage1: 1,
      ruleForm: {
        roleName: "",
        roleCode: "",
        roleEnabledState: ""
      },
      style: {},
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleType: [
          { required: false, message: "请选择角色类型", trigger: "change" }
        ]
      },
      form: {
        roleName: "",
        roleType: "",
        roleCode: "",
        roleEnabledState: "",
        remark: ""
      },
      editForm: {
        roleName: "",
        roleType: "",
        roleCode: "",
        roleEnabledState: "",
        remark: "",
        id: ""
      }
    };
  },

  mounted() {
    this.init();
  },
  computed: {},
  watch: {
    offForm: function(v) {
      if (v) {
        this.style = {
          height: "62px",
          overflow: "hidden"
        };
      } else {
        this.style = {
          height: "auto",
          overflow: "hidden"
        };
      }
    },
    showItemList(valArr) {
      for (let key in this.allItemList) {
        this.allItemList[key].show = false;
        for (let key1 in valArr) {
          if (this.allItemList[key].key == valArr[key1].key) {
            this.allItemList[key].show = true;
          }
        }
      }
      this.$nextTick(() => {
        this.$refs.dragTable.doLayout();
      });
    }
  },
  methods: {
    sizeChange1(n) {
      this.pageSize1 = n;
      this.getUserListByRoleId();
    },
    currentChange1(n) {
      this.currentPage1 = n;
      this.getUserListByRoleId();
    },
    addUserOk() {
      // console.log(this.$refs.user.selectedTableData)
      let checkedUsers = this.$refs.user.selectedTableData;
      let userids = "";
      checkedUsers.forEach(item => {
        userids += item.id + ",";
      });

      let params = {
        roleId: this.roleId,
        userIds: userids
      };
      addRoleUser(params).then(res => {
        this.dialogAllUser = false;
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
          this.getUserListByRoleId();
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    handleCheckedChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === defaultFormThead.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < defaultFormThead.length;
    },
    handleCheckAllChange(val) {
      this.showItemList = val ? defaultFormThead : [];
      this.isIndeterminate = false;
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "序号",
          "角色名称",
          "角色属性",
          "角色编码",
          "备注",
          "启用状态"
        ];
        const filterVal = [
          "id",
          "roleName",
          "roleType",
          "roleCode",
          "remark",
          "roleEnabledState"
        ];
        const data = this.formatJson(filterVal, this.tableData);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list-role"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      let i = 0;
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "id") {
            i++;
            return i;
          } else if (j === "roleEnabledState") {
            if (v[j] == 1) {
              return "启用";
            } else {
              return "禁用";
            }
          } else {
            return v[j];
          }
        })
      );
    },
    cancle() {
      this.dialogFormVisible = false;
      this.resetForm("addForm");
    },
    privilege(row) {
      this.roleId = row.id;
      this.$refs.qxDL.qxDialogShow = true;
    },
    showUser(row) {
      this.dialogUser = true;
      let id = row.id;
      this.roleId = id;
      this.getUserListByRoleId();
    },
    getUserListByRoleId() {
      let params = {
        pageNum: this.currentPage1,
        pageSize: this.pageSize1,
        roleId: this.roleId
      };
      getUserListByRoleId(params).then(res => {
        console.log(res);
        if (res.retHead.code == "0000000") {
          this.userTableData = res.retBody.list;
          this.total1 = res.retBody.total;
          this.currentPage1 = res.retBody.pageNum;
        } else {
          this.$message.error("发生错误！");
        }
      });
    },
    delUser(index, row) {
      let params = {
        roleId: this.roleId,
        userIds: row.id
      };
      delRoleUser(params).then(res => {
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
          this.getUserListByRoleId();
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    // showAssignUser(index, row) {},
    sizeChange(n) {
      this.pageSize = n;
      this.init();
    },
    currentChange(n) {
      this.currentPage = n;
      this.init();
    },
    init() {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...this.ruleForm
      };
      this.$api.formPost("/api/auth/sysrole/doGetList", params).then(res => {
        console.log(res);
        if (res.retHead.code == "0000000") {
          this.tableData = res.retBody.list;
          this.total = res.retBody.total;
          this.currentPage = res.retBody.pageNum;
          // this.setSort();//可移动
        }
      });
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      this.sortable = Sortable.create(el, {
        ghostClass: "sortable-ghost", // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          dataTransfer.setData("Text", "");
        },
        onEnd: evt => {
          const targetRow = this.tableData.splice(evt.oldIndex, 1)[0];
          this.tableData.splice(evt.newIndex, 0, targetRow);
        }
      });
    },
    showDialog() {
      this.dialogFormVisible = true;
      this.form.roleName = "";
    },
    showEditDialog(index, row) {
      this.editForm =JSON.parse(JSON.stringify(row));
      this.dialogEditVisible = true;
    },
    handleAdd() {
      // console.log()
      this.$refs.addForm.validate(valid => {
        this.form.changeUserId = JSON.parse(sessionStorage.getItem("user")).id;
        if (valid) {
          this.$api
            .formPost("/api/auth/sysrole/doSaveRole", this.form)
            .then(res => {
              console.log(res);
              // this.dialogFormVisible = false;
              if (res.retHead.code == "0000000") {
                this.dialogFormVisible = false;
                this.$message({
                  message: "添加成功！",
                  type: "success"
                });
                this.init();
                this.resetForm("addForm");
              } else {
                this.dialogFormVisible = true;
                this.$message({
                  message: "添加失败：" + res.retHead.message,
                  type: "error"
                });
              }
            });
        } else {
          this.$message.error("请完善表单！");
        }
      });
    },
    handleEdit() {
      this.$refs.editForm.validate(valid => {
        this.editForm.changeUserId = JSON.parse(
          sessionStorage.getItem("user")
        ).id;
        console.log(this.editForm)
        if (valid) {
          this.$api
            .formPost("/api/auth/sysrole/doModRole", this.editForm)
            .then(res => {
              this.dialogEditVisible = false;
              if (res.retHead.code == "0000000") {
                this.$message.success("执行成功！");
                this.init();
              } else {
                this.$message.error("执行失败！");
              }
            });
        } else {
          this.$message.error("请完善表单！");
        }
      });
    },

    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$api
            .formPost("/api/auth/sysrole/doDelRole", {
              id: row.id
              // changeUserId = JSON.parse(sessionStorage.getItem("user")).id,
            })
            .then(res => {
              if (res.retHead.code == "0000000") {
                this.$message({
                  message: "操作成功！",
                  type: "success"
                });
                this.init();
              } else {
                this.$message({
                  message: "操作失败！",
                  type: "error"
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    submitForm(formName) {
      this.init();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  created() {}
};
</script>
<style lang='scss' scoped>
// /deep/ .sortable-ghost  {
//   opacity: 0.8 !important;
//   color: #fff !important;
//   background: #42b983 !important;
// }
</style>